<template>
  <div class="register-container min-h-screen p-20px">
    <div class="content-wrapper m-auto flex items-center justify-between w-full max-w-1200px min-h-80vh rounded-12px overflow-hidden">
      <div class="header-section flex-1 flex flex-col justify-center items-center p-40px text-center md:p-30px 20px">
        <div class="header text-white font-bold text-[50px] mb-20px md:text-[36px]">广西工业产品信息对接平台</div>
        <div class="sub-header text-white font-bold text-[30px] md:text-[32px]">统一身份认证平台</div>
      </div>

      <div class="form-section flex-1 flex items-center justify-center p-40px md:p-20px">
        <div class="register-form w-full max-w-400px bg-[rgba(5,31,84,0.9)] rounded-8px p-30px md:max-w-full md:p-20px">
          <div class="welcome-text text-white text-center text-18px mb-30px md:text-16px">您好，欢迎登录!</div>

          <el-tabs
            class="login-tabs"
            v-model="activeTab"
            stretch
          >
            <el-tab-pane
              label="账号密码登录"
              name="passwordLogin"
            >
              <el-form
                ref="passwordLoginForm"
                :model="passwordLoginForm"
                :rules="passwordLoginRules"
                label-width="0px"
              >
                <el-form-item
                  prop="username"
                  class="mb-25px"
                >
                  <el-input
                    placeholder="请输入手机号"
                    v-model="passwordLoginForm.username"
                    autocomplete="off"
                  ></el-input>
                </el-form-item>

                <el-form-item
                  prop="password"
                  class="mb-25px"
                >
                  <el-input
                    type="password"
                    placeholder="请输入密码"
                    v-model="passwordLoginForm.password"
                    autocomplete="off"
                    show-password
                  ></el-input>
                </el-form-item>

                <el-form-item
                  prop="code"
                  class="mb-25px"
                >
                  <el-input
                    placeholder="请输入图形验证码"
                    v-model="passwordLoginForm.code"
                    autocomplete="off"
                    @keydown.enter.native="submitPasswordLoginForm"
                  >
                    <template #append>
                      <img
                        @click="getImgCaptcha"
                        class="captcha-image cursor-pointer h-38px w-100px object-cover rounded-4px"
                        :src="loginCaptchaObj?.img"
                      />
                    </template>
                  </el-input>
                </el-form-item>

                <el-form-item class="mb-25px">
                  <div
                    class="forgot-password text-right text-white text-14px mb-15px cursor-pointer hover:text-[#409EFF]"
                    @click="openDialog"
                  >
                    去重置密码
                  </div>
                  <el-button
                    type="primary"
                    :loading="loginLoading"
                    class="login-button w-full bg-[rgb(89,109,244)] border-[rgb(89,109,244)] h-40px text-16px"
                    @click="submitPasswordLoginForm"
                  >
                    登录
                  </el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>

            <el-tab-pane
              label="验证码登录"
              name="captchaLogin"
            >
              <el-form
                ref="phoneLoginForm"
                :model="phoneLoginForm"
                :rules="phoneLoginRules"
                label-width="0px"
              >
                <el-form-item
                  prop="mobile"
                  class="mb-25px"
                >
                  <el-input
                    placeholder="请输入手机号"
                    v-model="phoneLoginForm.mobile"
                    autocomplete="off"
                  ></el-input>
                </el-form-item>

                <el-form-item
                  prop="smsCode"
                  class="mb-25px"
                >
                  <el-input
                    placeholder="请输入验证码"
                    v-model="phoneLoginForm.smsCode"
                  >
                    <template #append>
                      <el-button
                        :disabled="countdown > 0"
                        @click="getSmsCode"
                        class="sms-button bg-[rgb(89,109,244)] border-[rgb(89,109,244)] text-white whitespace-nowrap"
                      >
                        {{ countdown > 0 ? `${countdown}秒` : '获取验证码' }}
                      </el-button>
                    </template>
                  </el-input>
                </el-form-item>

                <el-form-item
                  prop="code"
                  class="mb-25px"
                >
                  <el-input
                    placeholder="请输入图形验证码"
                    v-model="phoneLoginForm.code"
                    autocomplete="off"
                    @keydown.enter.native="submitphoneLoginForm"
                  >
                    <template #append>
                      <img
                        @click="getImgCaptcha"
                        class="captcha-image cursor-pointer h-38px w-100px object-cover rounded-4px"
                        :src="loginCaptchaObj?.img"
                      />
                    </template>
                  </el-input>
                </el-form-item>
              </el-form>

              <el-button
                type="primary"
                :loading="loginLoading"
                class="login-button w-full bg-[rgb(89,109,244)] border-[rgb(89,109,244)] h-40px text-16px"
                @click="submitphoneLoginForm"
              >
                登录
              </el-button>
            </el-tab-pane>
          </el-tabs>

          <div class="login-link text-center text-white mt-20px text-16px">
            没有账号? <a
              @click="goToRegister"
              class="text-[#add8e6] cursor-pointer no-underline hover:text-[#409EFF]"
            >立即注册</a>
          </div>
        </div>
      </div>
    </div>
    <div class="back-to-home">
      <el-button
        type="primary"
        @click="gotoHome"
      >返回首页</el-button>
    </div>
    <!-- 对话框部分保持不变 -->
    <el-dialog
      title="请输入图形验证码确认"
      width="400px"
      :visible.sync="showPhoneDialog"
    >
      <el-input
        v-model="imgcode"
        placeholder="请输入图形验证码"
      >
        <template #append>
          <img
            @click="getPhoneCaptcha"
            class="captcha-image cursor-pointer h-38px w-100px object-cover rounded-4px"
            :src="phoneCaptchaObj?.img"
          />
        </template>
      </el-input>
      <span
        slot="footer"
        class="dialog-footer flex justify-end"
      >
        <el-button
          @click="showPhoneDialog = false"
          class="ml-10px"
        >取 消</el-button>
        <el-button
          :loading="confirmLoading"
          type="primary"
          @click="getSmsCode"
          class="ml-10px"
        >
          确 定
        </el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="重置密码"
      :visible.sync="forgetPasswordDialog"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item
          label="手机号"
          prop="mobile"
        >
          <el-input
            v-model="form.mobile"
            class="form-input w-full"
          ></el-input>
        </el-form-item>

        <el-form-item
          label="输入验证码"
          prop="smsCode"
        >
          <el-input
            v-model="form.smsCode"
            class="form-input w-full"
          >
            <template #append>
              <el-button
                :disabled="countdown > 0"
                @click="getSmsCode"
              >
                {{ countdown > 0 ? `${countdown}秒` : '获取验证码' }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item
          label="输入密码"
          prop="password"
        >
          <el-input
            v-model="form.password"
            type="password"
            class="form-input w-full"
            show-password
          ></el-input>
        </el-form-item>

        <el-form-item
          label="确认密码"
          prop="confirmPassword"
        >
          <el-input
            v-model="form.confirmPassword"
            class="form-input w-full"
            type="password"
            show-password
          ></el-input>
        </el-form-item>
      </el-form>

      <span
        slot="footer"
        class="dialog-footer flex justify-end"
      >
        <el-button
          @click="forgetPasswordDialog = false"
          class="ml-10px"
        >取 消</el-button>
        <el-button
          :loading="confirmLoading"
          type="primary"
          @click="resetPassword"
          class="ml-10px"
        >
          重置密码
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getcode, sendSmsCode, smsLogin, forgetPassword } from "@/api/user";
import { setToken } from "@/utils/auth";

export default {
  name: "LoginPage",
  data() {
    // 表单验证规则
    const validateMobile = (rule, value, callback) => {
      const reg = /^1[3-9]\d{9}$/;
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else if (!reg.test(value)) {
        callback(new Error("请输入正确的手机号"));
      } else {
        callback();
      }
    };

    const validateUsername = (rule, value, callback) => {
      const regUsername =
        /^[A-Za-z\u4e00-\u9fa5][A-Za-z0-9\u4e00-\u9fa5_]{1,19}$/;
      const regPhone = /^1[3-9]\d{9}$/;
      if (value === "") {
        callback(new Error("请输入用户名或手机号码"));
      } else if (!regUsername.test(value) && !regPhone.test(value)) {
        callback(
          new Error(
            "用户名以中文或英文字母开头，包含中文、英文字母、数字和下划线，2-20位字符，或者手机号码"
          )
        );
      } else {
        callback();
      }
    };

    const validatePassword = (rule, value, callback) => {
      const reg =
        /^\S*(?=\S{8})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*?.])\S*$/;
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (!reg.test(value)) {
        callback(
          new Error(
            "密码长度8-20位，至少包含1个大写字母，1个小写字母，1个数字和一个特殊符号(!@#$%^&*?.)"
          )
        );
      } else {
        callback();
      }
    };

    const validateConfirmPassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.form.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };

    return {
      activeTab: "passwordLogin",
      countdown: 0,
      passwordLoginForm: {
        username: "",
        password: "",
        code: "",
        uuid: "",
      },
      phoneLoginForm: {
        mobile: "",
        code: "",
        smsCode: "",
        uuid: "",
      },
      passwordLoginRules: {
        username: [{ validator: validateUsername, trigger: "blur" }],
        password: [{ validator: validatePassword, trigger: "blur" }],
        code: [
          { required: true, message: "请输入图形验证码", trigger: "blur" },
        ],
      },
      phoneLoginRules: {
        mobile: [{ validator: validateMobile, trigger: "blur" }],
        smsCode: [{ required: true, message: "请输入验证码", trigger: "blur" }],
        code: [
          { required: true, message: "请输入图形验证码", trigger: "blur" },
        ],
      },
      formRules: {
        mobile: [
          { required: true, validator: validateMobile, trigger: "blur" },
        ],
        smsCode: [{ required: true, message: "请输入验证码", trigger: "blur" }],
        password: [
          { required: true, validator: validatePassword, trigger: "blur" },
        ],
        confirmPassword: [
          {
            required: true,
            validator: validateConfirmPassword,
            trigger: "blur",
          },
        ],
      },
      forgetPasswordDialog: false,
      form: {
        mobile: "",
        code: "",
        smsCode: "",
        password: "",
        confirmPassword: "",
        uuid: "",
      },
      loginCaptchaObj: {
        img: "",
        uuid: "",
      },
      phoneCaptchaObj: {
        img: "",
        uuid: "",
      },
      imgcode: "",
      showPhoneDialog: false,
      phoneScene: 1,
      loginLoading: false,
      confirmLoading: false,
    };
  },

  created() {
    this.getImgCaptcha();
  },

  methods: {
    // 获取图形验证码
    async getImgCaptcha() {
      try {
        const res = await getcode();
        this.loginCaptchaObj.img = "data:image/png;base64," + res.img;
        this.loginCaptchaObj.uuid = res.uuid;
      } catch (error) {
        console.error("获取图形验证码失败:", error);
      }
    },

    async getPhoneCaptcha() {
      try {
        const res = await getcode();
        this.phoneCaptchaObj.img = "data:image/png;base64," + res.img;
        this.phoneCaptchaObj.uuid = res.uuid;
      } catch (error) {
        console.error("获取手机验证图形验证码失败:", error);
      }
    },

    // 忘记密码相关方法
    openDialog() {
      this.forgetPasswordDialog = true;
    },

    passworkGetSmsCode() {
      this.$refs.form.validateField("mobile", (valid) => {
        if (!valid) {
          this.showPhoneDialog = true;
          this.phoneScene = 3; // 忘记密码场景
          this.getPhoneCaptcha();
        }
      });
    },

    // 获取短信验证码
    async getSmsCode() {
      const mobile =
        this.forgetPasswordDialog === false
          ? this.phoneLoginForm.mobile
          : this.form.mobile;

      // 设置场景：登录(2) 或 忘记密码(3)
      this.phoneScene = this.forgetPasswordDialog === false ? 2 : 3;
      this.confirmLoading = true;

      try {
        const res = await sendSmsCode({
          mobile,
          scene: this.phoneScene,
          code: this.imgcode,
          uuid: this.phoneCaptchaObj.uuid,
        });

        if (res.code === 200) {
          this.$message.success("验证码发送成功！");
          this.showPhoneDialog = false;
          this.startCountdown();
        } else {
          this.getPhoneCaptcha();
        }
      } catch (error) {
        console.error("发送短信验证码失败:", error);
        this.getPhoneCaptcha();
      } finally {
        this.confirmLoading = false;
      }
    },

    // 倒计时功能
    startCountdown() {
      this.countdown = 60;
      const timer = setInterval(() => {
        this.countdown--;
        if (this.countdown <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    },

    // 重置密码
    async resetPassword() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.confirmLoading = true;
          try {
            const res = await forgetPassword(this.form);
            if (res.code === 200) {
              this.$message.success("重置密码成功！");
              this.forgetPasswordDialog = false;
            }
          } catch (error) {
            console.error("重置密码失败:", error);
          } finally {
            this.confirmLoading = false;
          }
        }
      });
    },

    // 账号密码登录
    submitPasswordLoginForm() {
      this.$refs.passwordLoginForm.validate(async (valid) => {
        if (valid) {
          this.passwordLoginForm.uuid = this.loginCaptchaObj.uuid;
          this.loginLoading = true;

          try {
            this.$store
              .dispatch("user/login", this.passwordLoginForm)
              .then((res) => {
                if (res.code === 200) {
                  setToken(res.data.access_token);
                  this.$store.dispatch("user/getUserInfo").then((info) => {
                    if (info.companyId == null) {
                      this.$router.push({
                        name: "center",
                        query: { activeMenu: "personalCenter" },
                      });
                    } else {
                      this.$message.success("登录成功！");
                      this.$router.push({ path: "/" });``
                    }
                  });
                } else {
                  this.getImgCaptcha();
                }
              });
          } catch (error) {
            console.error("登录失败:", error);
            this.getImgCaptcha();
          } finally {
            this.loginLoading = false;
          }
        } else {
          return false;
        }
      });
    },

    // 手机验证码登录
    submitphoneLoginForm() {
      // 保持原方法名以确保兼容性
      this.$refs.phoneLoginForm.validate(async (valid) => {
        if (valid) {
          this.loginLoading = true;

          try {
            const params = {
              mobile: this.phoneLoginForm.mobile,
              smsCode: this.phoneLoginForm.smsCode,
              code: this.phoneLoginForm.code,
              uuid: this.loginCaptchaObj.uuid,
            };
            this.$store.dispatch("user/smsLogin", params).then((res) => {
              if (res.code === 200) {
                this.$message.success("登录成功！");
                setToken(res.data.access_token);
                this.$store.dispatch("user/getUserInfo").then((info) => {
                  if (info.companyId == null) {
                    this.$router.push({
                      name: "center",
                      query: { activeMenu: "personalCenter" },
                    });
                  } else {
                    this.$message.success("登录成功！");
                    this.$router.push({ path: "/" });
                  }
                });
              } else {
                this.getImgCaptcha();
              }
            });
          } catch (error) {
            console.error("手机登录失败:", error);
            this.getImgCaptcha();
          } finally {
            this.loginLoading = false;
          }
        } else {
          return false;
        }
      });
    },

    // 获取登录手机验证码
    getLoginPhoneCode() {
      this.$refs.phoneLoginForm.validateField("mobile", (valid) => {
        if (!valid) {
          this.showPhoneDialog = true;
          this.phoneScene = 2; // 登录场景
          this.getPhoneCaptcha();
        }
      });
    },

    // 页面跳转
    goToRegister() {
      this.$router.push({ path: "/register" });
    },

    gotoHome() {
      this.$router.push({ path: "/" });
    },
  },
};
</script>

<style scoped>
.register-container {
  background: url("@/assets/image/login_bg.png");
  background-size: cover;
}
.back-to-home {
  position: absolute;
  bottom: 20px;
  right: 20px;
}
.login-tabs ::v-deep .el-tabs__nav-wrap::after {
  display: none;
}

.login-tabs ::v-deep .el-tabs__item {
  color: white;
  font-size: 16px;
}

.login-tabs ::v-deep .el-tabs__item.is-active {
  color: #409eff;
}

.login-tabs ::v-deep .el-tabs__active-bar {
  background-color: #409eff;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .content-wrapper {
    flex-direction: column;
  }
}

@media (max-width: 576px) {
  .register-container {
    padding: 10px;
  }

  .content-wrapper {
    border-radius: 8px;
  }
}
</style>